import {
  createRouter,
  createWebHashHistory
} from 'vue-router'
import store from "@/store";
//vue中引用
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes = [

  {
    path: "/",
    name: '首页',
    component: () => import("../layout"),
    redirect: '/index',
    children: [
      {
        path: '/index',
        name: '首页',
        component: () => import("@/views/Index.vue"),
      },
      {
        path: '/userCenter',
        name: '个人中心',
        component: () => import("@/views/userCenter"),
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import("@/views/Login.vue"),
  },
  {
    path: '/404',
    name: '404',
    component: () => import("@/views/404.vue"),
  },

]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  },
})
// const modules = require.context("../views/", true, /\.vue$/)
router.beforeEach((to, from, next) => {
    NProgress.start();
    const whiteList = ["/login", "/404"];
    let token = sessionStorage.getItem("token");
    let hasRoutes = store.state.hasRoutes;
    let menuList = JSON.parse(sessionStorage.getItem("menuList"));
   
    if (token) {
        if (!hasRoutes) {
            bindRoute(menuList, to.path)
            store.commit("SET_ROUTES_STATE", true);
            next({
                ...to,
                replace: true
            })
        } else {
            if (flatten(router.options.routes).every((item => item.path !== to.path))) {
                sessionStorage.clear()
                router.replace("/login")
                router.history = [];
            } else {
                next()
            }
        }

    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next("/login")
        }
    }
})
//登录后
router.afterEach(transition => {
    NProgress.done();
});
//动态绑定路由
const bindRoute = (menuList, path) => {
    let newRoutes = router.options.routes;
    menuList.forEach((menu) => {
        if (menu.children) {
            menu.children.forEach(m => {
                let route = menuToRoute(m, menu.name);
                if (route) {
                    newRoutes[0].children.push(route);
                }
            })
        }
    })
    //重现添加到路由
    newRoutes.forEach(route => {
        router.addRoute(route);
    })
    if (flatten(newRoutes).every((item => item.path !== path))) {
        sessionStorage.clear()
        router.replace("/login")
        router.history = [];
    }

}
const flatten = (arr) => {
    return arr.reduce((pre, next) => {
        return pre.concat(next.children instanceof Array ? flatten(next.children) : next)
    }, [])
}
const filterMenu=[{
    path:'/sys/dictData/index',
    activeIndex:'/sys/dictType/index'
},{
    path:'/examManage/paperManage/joinPaper',
    activeIndex:'/examManage/paperManage/index'
}]
const menuToRoute = (menu, parentName) => {
    try{
        if (!menu.component) return null;
        else {
            let route=null
            let _t=null
            if(filterMenu.some((t)=>{
                _t=t;
                return t.path==menu.path;
            })){
                route = {
                    name: menu.name,
                    path: menu.path,
                    meta: {
                        parentName: parentName,
                        activeIndex:_t.activeIndex
                    }
                }
            }
            else{
                route = {
                    name: menu.name,
                    path: menu.path,
                    meta: {
                        parentName: parentName,
                    }
                }
            }
            
            route.component = () => import("../views/"+menu.component+".vue")
            return route;
        }
    }
    catch(e){
        return null;
    }
  
}
export default router

